package jmine.tec.hydra.codec.impl;

import jmine.tec.hydra.HydraMessages;
import jmine.tec.hydra.api.HydraMessage;
import jmine.tec.hydra.codec.Decoder;
import jmine.tec.hydra.exception.HydraException;
import jmine.tec.hydra.script.DecodeResult;
import jmine.tec.hydra.script.DecodeScriptContext;
import jmine.tec.script.ScriptExecutorException;
import jmine.tec.script.persistent.domain.Script;

/**
 * Decodificador de mensagens via script.
 * 
 * @author piercio
 */
public class ScriptDecoder implements Decoder {

    private final Script decodeScript;

    /**
     * Construtor.
     * 
     * @param script o script de decodificação.
     */
    public ScriptDecoder(Script script) {
        this.decodeScript = script;
    }

    /**
     * {@inheritDoc}
     */
    public DecodeResult decode(HydraMessage message) {
        return this.runScript(message);
    }

    /**
     * Executa o script.
     * 
     * @param message message
     * @return services
     */
    private DecodeResult runScript(HydraMessage message) {
        try {
            return this.decodeScript.createContext(DecodeScriptContext.class).prepare(message).dispatchExecution();
        } catch (ScriptExecutorException e) {
            throw new HydraException(HydraMessages.BSH_DECODE.create(this.decodeScript.getMnemonico()), e);
        }
    }
}
